package com.bum.app.tool.fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

@SuppressWarnings("serial")
public class FetchServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");

		String url = req.getParameter("url");
		if (url != null) {
			try {
				url = URLDecoder.decode(url, "utf-8");

				URL u = new URL(url);
				InputStream is = u.openStream();

				String callback = req.getParameter("callback");
				if (StringUtils.isNotEmpty(callback)) {
					resp.setContentType("application/json");
					String text = IOUtils.toString(is, "UTF-8");
					if (text != null) {
						text = text.replaceAll("[\n\r]", "").replaceAll("[\\s]+", " ").replace("\"", "\\\"");
						text = callback + "(\"" + text + "\")";
						IOUtils.write(text.getBytes("UTF-8"), resp.getOutputStream());
					}
				} else {
					resp.setContentType("text/plain");
					IOUtils.copy(is, resp.getOutputStream());
				}
			} catch (Throwable e) {
				resp.getWriter().write(e.getMessage());
			}
		}
	}
}
